#!/usr/env/bin python
# -*- coding: utf-8 -*-

# @Time    : 2018/10/16 08:52
# @Author  : yangdy
# @Email   : yangdy@egu360.com
# @File    : qywechat-mail.py
# @Software: PyCharm

import os
import smtplib

from email import encoders
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
from email.mime.audio import MIMEAudio
from email.mime.application import MIMEApplication
from email.utils import formataddr
from email.utils import parseaddr
from email.header import Header


def format_addr(s):
    name, addr = parseaddr(s)
    return formataddr((Header(name, 'utf-8').encode(), addr))


def main():
    print('hello')

    print(os.path)

    from_addr = 'yangdy@egu360.com'
    # password = 'Ydy3236283'
    password = 'GkR7yP4T4o8j4wvs'
    receivers = ['137740537@qq.com', 'caott@egu360.com',
                 'wenjing@egu360.com', 'liangpp@egu360.com',
                 'fanss@egu360.com']
    # receivers = ['137740537@qq.com', ]

    smtp_server = 'smtp.exmail.qq.com'
    smtp_port = 465

    # plain 邮件
    # msg = MIMEText('hello, It\'s a test ^_^', 'plain', 'utf-8')
    # html 邮件
    # msg = MIMEText('<html><body><h1>Hello</h1>' +
    #                '<p>send by <a href="http://www.python.org">Python</a>...</p>' +
    #                '</body></html>', 'html', 'utf-8')
    # multipart
    msg_root = MIMEMultipart('related')

    msg_al = MIMEMultipart('alternative')
    msg_root.attach(msg_al)

    msg_root['From'] = format_addr('定一 <%s>' % from_addr)
    # msg['To'] = format_addr('To <%s>' % to_addr)
    # msg['To'] = formataddr([Header('自定义收信昵称', 'utf-8'), to_address])
    # msg['To'] = Header('自定义收信昵称', 'utf-8')
    msg_root['To'] = formataddr(['大家', ''.join(receivers)])
    msg_root['Subject'] = Header('hello subject', 'utf-8').encode()

    file_jpg_name = 'test.jpg'
    with open(file_jpg_name, 'rb') as file_jpg:
        print(file_jpg.name)
        print(os.path.splitext(file_jpg.name))
        # 设置附件的MIME和文件名，这里是png类型:
        mime = MIMEBase('image', 'png', filename=file_jpg.name)
        # 加上必要的头信息:
        mime.add_header('Content-Disposition', 'attachment', filename='test.png')
        mime.add_header('Content-ID', '<0>')
        mime.add_header('X-Attachment-Id', '0')
        # 把附件的内容读进来:
        mime.set_payload(file_jpg.read())
        # 用Base64编码:
        encoders.encode_base64(mime)
        # 添加到MIMEMultipart:
        msg_root.attach(mime)
        file_jpg.close()

    with open('test1.png', 'rb') as f:
        mime = MIMEApplication(f.read())
        mime.add_header('Content-ID', '<image1>')
        mime.add_header('Content-Disposition', 'attachment', filename='test11.png')
        msg_root.attach(mime)
        f.close()

    with open('hello.txt', 'rb') as f:
        mime = MIMEText(f.read(), 'base64', 'utf-8')
        mime.add_header('Content-Disposition', 'attachment', filename=f.name)
        msg_root.attach(mime)
        f.close()

    with open('test.jpg', 'rb') as f:
        text = MIMEText("""
            <table border='1'>
                <tbody>
                    <tr>
                        <td>名称</td><td>hello</td>
                    </tr>
                    <tr>
                        <td>图片</td><td><img src="cid:image1" width='120'></td>
                    </tr>
                </tbody>
            </table>
        """, 'html', 'utf-8')
        msg_al.attach(text)
        mime = MIMEImage(f.read())
        mime.add_header('Content-ID', '<image1>')
        msg_root.attach(mime)

    # text = MIMEText('<html><body><h1>Hello</h1>' +
    #                 '<p>send by <a href="http://www.python.org">Python</a>...</p>' +
    #                 '</body></html>', 'html', 'utf-8')
    # msg_al.attach(text)

    with open('hahaha.pptx', 'rb') as f:
        mime = MIMEApplication(f.read())
        mime.add_header('Content-Disposition', 'attachment', filename=f.name)
        msg_root.attach(mime)

    with open('hahaha.pdf', 'rb') as f:
        mime = MIMEApplication(f.read())
        mime.add_header('Content-Disposition', 'attachment', filename=f.name)
        msg_root.attach(mime)

    with open('hahaha.docx', 'rb') as f:
        mime = MIMEApplication(f.read())
        mime.add_header('Content-Disposition', 'attachment', filename=f.name)
        msg_root.attach(mime)

    with open('hahaha.xlsx', 'rb') as f:
        mime = MIMEApplication(f.read())
        mime.add_header('Content-Disposition', 'attachment', filename=f.name)
        msg_root.attach(mime)

    with open('diamonds.mp3', 'rb') as f:
        mime = MIMEAudio(f.read(), 'mp3')
        mime.add_header('Content-Disposition', 'attachment', filename=f.name)
        msg_root.attach(mime)

    try:
        print('init server')
        # smtp_obj = smtplib.SMTP(smtp_server, smtp_port)
        smtp_obj = smtplib.SMTP_SSL(host=smtp_server, port=smtp_port)
        # smtp_obj.ehlo()
        # smtp_obj.starttls()
        print('set_debuglevel')
        smtp_obj.set_debuglevel(1)
        print('login')
        # smtp_obj.login(from_addr, 'jcxpvvzhpujncbca')
        smtp_obj.login(from_addr, password)
        print('send mail')
        smtp_obj.sendmail(from_addr, receivers, msg_root.as_string())
        print('quit')
        smtp_obj.quit()
    except smtplib.SMTPConnectError as e:
        print('邮件发送失败，连接失败:', e.smtp_code, e.smtp_error)
    except smtplib.SMTPAuthenticationError as e:
        print('邮件发送失败，认证错误:', e.smtp_code, e.smtp_error)
    except smtplib.SMTPSenderRefused as e:
        print('邮件发送失败，发件人被拒绝:', e.smtp_code, e.smtp_error)
    except smtplib.SMTPRecipientsRefused as e:
        print('邮件发送失败，收件人被拒绝:', e.smtp_code, e.smtp_error)
    except smtplib.SMTPDataError as e:
        print('邮件发送失败，数据接收拒绝:', e.smtp_code, e.smtp_error)
    except smtplib.SMTPException as e:
        print('邮件发送失败, ', e.message)
    except Exception as e:
        print('邮件发送异常, ', str(e))


if __name__ == '__main__':
    main()
